import os
import base64
import main

from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from theme import render

class BasecampAccount(db.Model):
    '''Basecamp account model'''

    owner    = db.UserProperty(required=True)
    username = db.StringProperty(required=True)
    password = db.StringProperty(required=True)
    link     = db.LinkProperty(required=True)

class Login(webapp.RequestHandler):
    '''Display login form'''
    
    def get(self):
        user = users.get_current_user()

        if user:
            if BasecampAccount.gql("WHERE owner = :1", user).fetch(1):
                self.redirect('/')
            else:
                self.redirect('/account')
        else:
            self.redirect(users.create_login_url(self.request.uri))

class BasecampAccountForm(webapp.RequestHandler):
    '''Display from to keep user's basecamp account information'''

    def get(self):
        if not is_login():
            self.redirect('/')
        else:
            user = users.get_current_user()
            accounts = BasecampAccount.gql("WHERE owner = :1", user).fetch(1)
            if len(accounts) == 1:
                account = accounts.pop()
                values = {
                    'link': account.link,
                    'user': account.username,
                    'pass': account.password,
                }
            else:
                values = {}

            path = 'templates/basecamp_account_form.html'
            mainpage = main.MainPage()
            modules = mainpage.load_module(only_name=True) 
            self.response.out.write(render(path, values, 'Set Basecamp account', ["bc_acc_form.css"], modules))

    def post(self):
        user = users.get_current_user()
        accounts = BasecampAccount.gql("WHERE owner = :1", user).fetch(1) 
        values = (user,
                  self.request.get('user'),
                  base64.standard_b64encode(self.request.get('pass')),
                  self.request.get('url'))

        if len(accounts) == 1:
            account = accounts.pop()
            account.username = values[1]
            account.password = values[2]
            account.link = values[3]
        else:
            account = BasecampAccount(owner = values[0],
                                      username = values[1],
                                      password = values[2],
                                      link = values[3])
			

        account.put()
        self.redirect('/')


def is_login():
    return get_current_user()

def get_current_user():
    return users.get_current_user()

def get_current_user_account():
    return get_user_account()

def get_user_account(user=get_current_user()):
    return BasecampAccount.gql("WHERE owner = :1", user).get()
